//$(document).ready(function() {
var admin_IaaS = function() {

    function adminloadSites() {
        for (var i = 0; i < allsites.length; i++) {
            var sites = new Option(allsites[i], allsites[i]);
            $("#preferredSiteComboBox")[0].options.add(sites);
        }
    };
    function adminDeleteVM(siteName, vmid) {
        var back;
        $.post('/' + siteName + '/admin/execute_wait/iaas.vm_delete.json', {
            user: userid,
            vm_id: vmid
        },
        function(serverResponse) {
            if (serverResponse[0] === true) {
                back = 1;
            }
            else {
                alert(serverResponse[0] + serverResponse[1]);
                back = 0;
            }
        },
        'json');
        return back;
    };
    function actResult(status, act, vmid) {
        var j, node, vm;
        if (status == 'success') {
            alert(act + ' ' + vmid + ' success');
            if (act == 'delete' || act == 'shutdown') {
                for (j = $('#adminIaaSVirtualMachineTable').dataTable().fnSettings().aoData.length - 1; j >= 0; j--) {
                    vm = $('#adminIaaSVirtualMachineTable').dataTable().fnSettings().aoData[j]._aData[0];
                    if (vm == vmid) {
                        node = $('#adminIaaSVirtualMachineTable').dataTable().fnGetNodes(j);
                        $('#adminIaaSVirtualMachineTable').dataTable().fnDeleteRow(node);
                    }
                }
            }
            else {
                for (j = $('#adminIaaSVirtualMachineTable').dataTable().fnSettings().aoData.length - 1; j >= 0; j--) {
                    vm = $('#adminIaaSVirtualMachineTable').dataTable().fnSettings().aoData[j]._aData[0];
                    if (vm == vmid) {
                        node = $('#adminIaaSVirtualMachineTable').dataTable().fnGetNodes(j);
                        var newState = '';
                        if (act === 'suspend') newState = 'SUSPENDED';
                        if (act === 'resume') newState = 'RUNNING';
                        if (act === 'stop') newState = 'STOPPED';
                        $('#adminIaaSVirtualMachineTable').dataTable().fnUpdate(newState, node, 9, 0);
                    }
                }
            }
        }
        else {
            alert(vmid + ' ' + status);
        }
    };
    function adminAct(siteName, act, vmid, callback) {
        if (act == 'delete') {
            $.post('/' + siteName + '/admin/execute_wait/iaas.vm_delete.json', {
                user: userid,
                vm_id: vmid
            },
            function(serverResponse) {
                if (serverResponse[0] === true) {
                    callback('success', act, vmid);
                }
                else {
                    callback(serverResponse[0] + serverResponse[1], act, vmid);
                }
            },
            'json');
        }
        else {
            $.post('/' + siteName + '/admin/execute_wait/iaas.vm_action.json', {
                user: userid,
                action: act,
                vm_id: vmid
            },
            function(serverResponse) {
                if (serverResponse[0] === true) {
                    callback("success", act, vmid);
                }
                else {
                    callback(serverResponse[0] + serverResponse[1], act, vmid);
                }
            },
            'json');
        }
    };
    function adminaction() {
        var anSelected = fnGetSelected(adminIaaSVirtualMachineTable);
        var a = $('td', anSelected);
        if (a.length === 0) {
            alert("please select one row!");
            return 0;
        }
        var act = $("#adminIaaSVMActionField")[0].value;
        for (var j = 0; j < anSelected.length; ++j) { (function(selectedVM) {
                var vmid = $($('td', selectedVM)[0]).text();
                var siteName = $($('td', selectedVM)[5]).text();
                adminAct(siteName, act, vmid, actResult);
            })(anSelected[j]);
        }
    };
    function getAdminIaaSHosts(callback) {
        for (var j = 0; j < allsites.length; ++j) { (function(siteName) {
                $.get('/' + siteName + '/admin/execute_wait_cacheable/iaas.get_hostpool_info.json', {},
                function(serverResponse) {
                    var hostname;

                    var hostid;

                    var cpus;

                    var cpuused;

                    var mem;

                    var freemem;

                    var hostedvm;
                    var hostData = [];
                    if (serverResponse[0] === false) {
                        return;
                    }
                    for (var i = 0; i < serverResponse[1].length; i++) {
                        hostname = serverResponse[1][i].name;

                        hostid = serverResponse[1][i].guid;

                        cpus = serverResponse[1][i].totalCpu / 100;

                        cpuused = serverResponse[1][i].usedCpu / 100;

                        mem = serverResponse[1][i].totalMemory / 1024;

                        freemem = serverResponse[1][i].freeMemory / 1024;
                        hostedvm = serverResponse[1][i].virtualMachines;
                        hostData.push([siteName, hostname, hostid, cpus, cpuused, mem, freemem, hostedvm]);
                        /*$('#adminIaaSHostMachineTable').dataTable().fnAddData([
					siteName,
					hostname,
					hostid,
					cpus,
					cpuused,
					mem,
					freemem,
					hostedvm,
					]);*/
                    }
                    callback(siteName, hostData);

                },
                'json');
            })(allsites[j]);
        }
    };
    function loadadminIaaSHosts(siteName, hostData) {
        for (var j = $('#adminIaaSHostMachineTable').dataTable().fnSettings().aoData.length - 1; j >= 0; j--) {
            var name = $('#adminIaaSHostMachineTable').dataTable().fnSettings().aoData[j]._aData[0];
            if (name == siteName) {
                var node = $('#adminIaaSHostMachineTable').dataTable().fnGetNodes(j);
                $('#adminIaaSHostMachineTable').dataTable().fnDeleteRow(node);
            }
        }
        $('#adminIaaSHostMachineTable').dataTable().fnAddData(hostData);
    };
    function getAdminIaaSVMs(callback) {
        for (var j = 0; j < allsites.length; ++j) { (function(siteName) {
                $.get('/' + siteName + '/admin/execute_wait_cacheable/iaas.get_vms_info.json', {},
                function(serverResponse) {
                    var hostMachine;
                    var vmid;
                    var vmip;
                    var vmport;
                    var vmname;
                    var vcpus;
                    var memory;
                    var stat;
                    var ipv6address;
                    var owner;
                    var starttime;
                    var tableData = [];
                    if (serverResponse[0] === false) {
                        return;
                    }
                    for (var i = 0; i < serverResponse[1].length; i++) {
                        vmid = serverResponse[1][i].guid;
                        vmname = serverResponse[1][i].name;
                        if (serverResponse[1][i].ipv6) {
                            ipv6address = serverResponse[1][i].ipv6;
                        }
                        else {
                            ipv6address = 'NOT AVAILABLE';
                        }
                        vmip = serverResponse[1][i].ip;
                        vmport = serverResponse[1][i].port;
                        vcpus = serverResponse[1][i].cpu;
                        memory = serverResponse[1][i].memory;
                        hostMachine = serverResponse[1][i].hostMachine;
                        owner = serverResponse[1][i].owner;
                        stat = serverResponse[1][i].stat;
                        starttime = serverResponse[1][i].stime;
                        tableData.push([vmid, vmname, ipv6address, vcpus, memory, siteName, hostMachine, owner, starttime, stat]);
                    }
                    callback(siteName, tableData);
                },
                'json');
            })(allsites[j]);
        }
    };
    function loadadminIaaSVMs(siteName, tableData) {
        for (var j = $('#adminIaaSVirtualMachineTable').dataTable().fnSettings().aoData.length - 1; j >= 0; j--) {
            var name = $('#adminIaaSVirtualMachineTable').dataTable().fnSettings().aoData[j]._aData[5];
            if (name == siteName) {
                var node = $('#adminIaaSVirtualMachineTable').dataTable().fnGetNodes(j);
                $('#adminIaaSVirtualMachineTable').dataTable().fnDeleteRow(node);
            }
        }
        $('#adminIaaSVirtualMachineTable').dataTable().fnAddData(tableData);
    };
    function createAndDeleteResult(status) {
        alert(status);
    };
    function createHost(siteName, hostname, vmtype, callback) {
        $.post('/' + siteName + '/admin/execute_wait/iaas.host_create.json', {
            host_ip: hostname,
            virt: vmtype
        },
        function(serverResponse) {
            if (serverResponse[0]) {
                callback("create host " + hostname + " succeed ");
            }
            else {
                callback("create host fail" + serverResponse[1] + hostname + vmtype);
            }
        },
        'json');
    };

    function deleteHost(siteName, deleteid, deletehost, callback) {
        $.post('/' + siteName + '/admin/execute_wait/iaas.host_delete.json', {
            host_id: deleteid
        },
        function(serverResponse) {
            if (serverResponse[0]) {
                callback("delete " + deletehost + " success");
            }
            else {
                callback("delete " + deletehost + " fail" + serverResponse[1]);
            }
        });
    };

    $('#adminIaaSAddHostDialog').dialog({
        modal: false,
        autoOpen: false,
        title: 'Create VM',
        width: 450,
        buttons: {
            Confirm: function(event) {
                $("#craneModalDialogContent").text("add the host?");
                $('#craneModalDialog').dialog({
                    buttons: {
                        Confirm: function() {
                            var siteName = $("#preferredSiteComboBox")[0].value;
                            var hostname = $("#adminIaaSHostNameField")[0].value;
                            var vmtype = $("#adminIaaSVMTypeField")[0].value;
                            createHost(siteName, hostname, vmtype, createAndDeleteResult);
                            $(this).dialog('close');
                        },
                        Cancel: function() {
                            $(this).dialog('close');
                        }
                    }
                }).dialog('open');
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });
    $("#adminIaaSAddButton").click(function(event) {
        $('#adminIaaSAddHostDialog').dialog('open');
    });
    $("#adminIaaSDeleteButton").click(function(event) {
        var anSelected = fnGetSelected(adminIaaSHostMachineTable);
        var selectedHost = $('td', anSelected);
        var deleteid = $(selectedHost[2]).text();
        var deletehost = $(selectedHost[1]).text();
        if (selectedHost.length === 0) {
            alert("please select one row!");
            return 0;
        }
        $("#craneModalDialogContent").text("delete the host?");
        $('#craneModalDialog').dialog({
            buttons: {
                Confirm: function() {
                    var siteName = $("#preferredSiteComboBox")[0].value;
                    deleteHost(siteName, deleteid, deletehost, createAndDeleteResult);
                    $(this).dialog('close');
                },

                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        }).dialog('open');
    });
    $("#adminIaaSVMActionConfirm").click(function(event) {
        var anSelected = fnGetSelected(adminIaaSVirtualMachineTable);
        var selectedVM = $('td', anSelected);
        if (selectedVM.length === 0) {
            alert("please select one row!");
            return 0;
        }
        var vmid = $(selectedVM[0]).text();
        var act = $("#adminIaaSVMActionField")[0].value;
        $("#craneModalDialogContent").text("are you sure to " + act);
        $('#craneModalDialog').dialog({
            buttons: {
                Confirm: function() {
                    adminaction();
                    $(this).dialog('close');
                },

                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        }).dialog('open');

    });
    $("#adminIaaSHostRefreshButton").click(function(event) {
        getAdminIaaSHosts(loadadminIaaSHosts);
    });
    $("#adminIaaSVMRefreshButton").click(function(event) {
        getAdminIaaSVMs(loadadminIaaSVMs);
    });
    getAdminIaaSHosts(loadadminIaaSHosts);
    getAdminIaaSVMs(loadadminIaaSVMs);
    adminloadSites();
};
